package ${packageName}.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

<#if theme == "前后端分离响应式">
import com.fasterxml.jackson.databind.ObjectMapper;
import ${packageName}.constant.ResultConstant;
import ${packageName}.entity.CommonResult;
import java.io.PrintWriter;
</#if>
import ${packageName}.entity.User;

public class MVCInterceptor extends HandlerInterceptorAdapter{

	/**
	 * Handler执行之前调用这个方法
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		// 预请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
		
		HttpSession session = request.getSession();

		User user = (User) session.getAttribute("user");

		if (user == null) {
			<#if theme == "经典后台Thymleaf版">
			response.sendRedirect(request.getServletContext().getContextPath() + "/login");
            return false;
            </#if>
            <#if theme == "前后端分离响应式">
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            CommonResult commonResult = new CommonResult(ResultConstant.PLEASELOGIN_CODE, ResultConstant.FAIL_MSG);
            String result = new ObjectMapper().writeValueAsString(commonResult);
            response.setContentType("application/json; charset=utf-8");
            response.setCharacterEncoding("utf-8");
            PrintWriter pw = response.getWriter();
            pw.write(result);
            pw.flush();
            pw.close();
            return false;
            </#if>
		}
		return true;
	}

	/**
	 * Handler执行完成之后调用这个方法
	 */
	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse resp, Object handle, Exception ex)
			throws Exception {
		//System.out.println("出拦截器");
	}

	/**
	 * Handler执行之后，ModelAndView返回之前调用这个方法
	 */
	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse resp,
			Object handle, ModelAndView mav) throws Exception {
		//System.out.println("拦截器执行中……");
	}

}
